import React, { useState, useContext } from "react";


type AppContextType = { count: number, setCount: React.Dispatch<React.SetStateAction<number>> }

//1.创建context对象
const AppContext = React.createContext<AppContextType>({} as AppContextType)


// 创建一个wrapper组件
export const AppContextWrapper:React.FC<React.PropsWithChildren> = (props)=>{
  const [count, setCount] = useState(0)
  return(
    // {props.children} 这里使用了插槽  即是 levelA
    <AppContext.Provider value={{ count, setCount }}>{props.children}</AppContext.Provider>
  )
}


export const LevelA: React.FC = () => {
    const ctx =  useContext(AppContext)
    return (
        <div className="levelA">
            <h3>count的值是：{ctx.count}</h3>
            <button onClick={() => { ctx.setCount(prev => prev + 1) }}>+1</button>

            <LevelB />
        </div>
    )
}

const LevelB: React.FC = () => {
    return (
        <div className="levelB">
            <LevelC />
        </div>
    )
}


const LevelC: React.FC = () => {
    const ctx = useContext(AppContext)
    const add = () => {
        ctx.setCount((prev) => prev + 1)
    }
    const reset = ()=>{
        ctx.setCount(() => 0)
    }
    return (
        <div className="levelC">
            <p>count的值是：{ctx.count}</p>
            <button onClick={add}>+1</button>
            <button onClick={reset}>重置</button>
        </div>
    )
}


